package com.bw.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.entity.customer.PiCustomer;
import com.bw.entity.dc.PiLinkman;
import com.bw.entity.dc.PiMaterial;
import com.bw.entity.dc.PiProcess;
import com.bw.entity.order.*;
import com.bw.entity.order.center.OrderAndPrice;
import com.bw.entity.user.TbUser;
import com.bw.mapper.customer.PiCustomerMapper;
import com.bw.mapper.dc.PiLinkmanMapper;
import com.bw.mapper.dc.PiMaterialMapper;
import com.bw.mapper.dc.PiProcessMapper;
import com.bw.mapper.order.*;
import com.bw.req.OrderItem;
import com.bw.req.OrderPri;
import com.bw.req.XsPhoto;
import com.bw.service.order.IPiOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yzz
 * @since 2020-06-20
 */
@Service
public class PiOrderServiceImpl extends ServiceImpl<PiOrderMapper, PiOrder> implements IPiOrderService {
    @Autowired
    private PiOrderPicMapper piOrderPicMapper;

    @Autowired
    private PiOrderMapper orderMapper;

    @Autowired
    private PiCustomerMapper customerMapper;

    @Autowired
    private PiLinkmanMapper linkmanMapper;

    @Autowired
    private PiOrderItemMapper orderItemMapper;//零件表

    @Autowired
    private PiOrderItemMaterialMapper orderItemMaterialMapper;//零件材料

    @Autowired
    private PiMaterialMapper materialMapper;//材料

    @Autowired
    private PiOrderItemProcessMapper orderItemProcessMapper;//零件工序

    @Autowired
    private PiProcessMapper processMapper;//工序

    private final String path="E:\\photouploda\\xxx";

    //定义日志工具
    private final Logger log = LoggerFactory.getLogger(PiOrderServiceImpl.class);

    @Override
    public List<PiOrder> getOrderAndPrice() {
        return orderMapper.getOrderAndPrice();
    }

    @Override
    @Transactional
    public void improtPic(MultipartFile file, String code) throws Exception {//图片导入
        String fileName=file.getOriginalFilename();//文件的名称
        String itemCode=fileName.substring(0,fileName.lastIndexOf("."));//图号
        String exe=fileName.substring(fileName.lastIndexOf("."),fileName.length());//后缀
        String uuid= UUID.randomUUID().toString().replaceAll("-","");//随机生成id
        String dirPaht=path+"/"+code+"/";//图纸的存储目录按照订单编号区分文件夹

        File dirfile1 = new File(dirPaht);
        if(!dirfile1.exists()){
            dirfile1.mkdir(); //如果不存在问价夹就创建
        }

        PiOrderPic piOrderPic = new PiOrderPic();
        piOrderPic.setCode(code);
        piOrderPic.setFilePath("/"+code+"/"+uuid+exe);
        piOrderPic.setFileSize(String.valueOf(file.getSize()));
        piOrderPic.setName(itemCode);
        file.transferTo(new File(path+piOrderPic.getFilePath()));
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("code",piOrderPic.getCode());
        wrapper.eq("name",piOrderPic.getName());
        PiOrderPic pic = piOrderPicMapper.selectOne(wrapper);
        if(pic!=null){
            File file1 = new File(path + pic.getFilePath());
            file1.delete();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code",piOrderPic.getCode());
            queryWrapper.eq("name",piOrderPic.getName());
            piOrderPicMapper.update(piOrderPic,queryWrapper);
        }else {
            piOrderPicMapper.insert(piOrderPic);
        }
    }

    @Override
    @Transactional
    public InputStream preView(String orderCode, String itemCode) throws FileNotFoundException {//图片显示
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("code",orderCode);
        wrapper.eq("name",itemCode);
        PiOrderPic pic = piOrderPicMapper.selectOne(wrapper);
        if(pic != null){
            FileInputStream inputStream = new FileInputStream(path + pic.getFilePath());
            return inputStream;
        }
        return null;
    }

    /**
     * 查询导出数据，并放入对象中
     * @param id
     * @return
     */
    @Override
    public OrderPri findList(Long id) {
        OrderPri orderPri = new OrderPri();//创建对象用于装数据
        PiOrder piOrder = orderMapper.selectById(id);//查询对应订单
        PiCustomer piCustomer = customerMapper.selectById(piOrder.getCustomerId());//查询对应的公司
        orderPri.setCustomer(piCustomer);//公司信息存入
        PiLinkman linkman = linkmanMapper.selectById(piOrder.getLinkmanId());//查询对应联系人存入
        orderPri.setLinkman(linkman);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("orderId", id);
        List<PiOrderItem> list = orderItemMapper.selectList(queryWrapper);//订单相关的零件信息
        ArrayList<OrderItem> orderItems = new ArrayList<>();
        BigDecimal lastPrice = new BigDecimal('0');//-------总计
        for (PiOrderItem poi : list) {//分别存入零件信息
            OrderItem orderItem = new OrderItem();
            orderItem.setNo(poi.getSn());
            orderItem.setCode(poi.getCode());
            orderItem.setName(poi.getName());
            //零件材料存入
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("orderItemId", poi.getId());
            List<PiOrderItemMaterial> marterlist = orderItemMaterialMapper.selectList(queryWrapper1);
            String name = "";//材料名拼接
            BigDecimal materialcost = new BigDecimal('0');//材料价格合计
            for (PiOrderItemMaterial pim : marterlist) {
                PiMaterial material = materialMapper.selectById(pim.getMaterialId());
                name = name + "," + material.getName();
                BigDecimal materCost = pim.getMaterCost();
                materCost=materCost.multiply(new BigDecimal(poi.getNum()));//当前零件总量的材料费
                materialcost = materialcost.add(materCost);//材料的总价格
            }
            orderItem.setMaterialcost(materialcost);
            if (name != "") {
                name = name.substring(1);
            }
            orderItem.setMaterialname(name);//截取后的名字存入
            //表面积
            List<PiOrderItemProcess> processeslist = orderItemProcessMapper.selectList(queryWrapper1);
            String bcname = "";
            double time = 0;
            BigDecimal workcost = new BigDecimal('0');
            BigDecimal heatcost = new BigDecimal('0');//热处理
            BigDecimal surfacecost = new BigDecimal('0');//表面处理
            for (PiOrderItemProcess pop : processeslist) {//零件工序集合
                PiProcess process = processMapper.selectById(pop.getProcessId());
                bcname += "," + process.getName();
                if (process.getctype() == 2) {//表面积
                    BigDecimal proCost = pop.getProCost();
                    proCost=proCost.multiply(new BigDecimal(poi.getNum()));//表面积--工序总量的费用
                    surfacecost = surfacecost.add(proCost);//工时合计
                }
                if (process.getctype() == 1) {//重量
                    BigDecimal proCost = pop.getProCost();
                    proCost=proCost.multiply(new BigDecimal(poi.getNum()));//重量--工序总量的费用
                    heatcost = heatcost.add(proCost);
                }
                time += pop.getSgWorkHour()*poi.getNum();//单个工时*零件个数
                BigDecimal proCost = pop.getProCost();
                proCost=proCost.multiply(new BigDecimal(poi.getNum()));//当前工序总量的费用
                workcost = workcost.add(proCost);//时间-工序花费合计
            }
            if (bcname != "") {
                bcname = bcname.substring(1);
            }
            orderItem.setBcnames(bcname);//工序名存入
            orderItem.setTotal(poi.getNum());//零件数量
            orderItem.setWorkhour(time);//总工时（不包含准备工时）
            orderItem.setWorkcost(workcost);//时间工序花费（总）
            orderItem.setHeatcost(heatcost);//重量工序花费（总）
            orderItem.setSurfacecost(surfacecost);//表面工序花费（总）
            //（加工+材料）*(1+税率)
            BigDecimal sum = new BigDecimal('0');
            sum = sum.add(materialcost);
            sum = sum.add(workcost);
            sum = sum.add(heatcost);
            sum = sum.add(surfacecost);//含税总价(加工+材料）
            BigDecimal sgPrice = new BigDecimal('0');
            sgPrice = sum.divide(new BigDecimal(poi.getNum()));
            orderItem.setProductprice(sgPrice);//-------含税单价价格1
            //-------------------
            orderItem.setTotalprice(sum);//-------------------总价1
            //-------------------
            lastPrice = lastPrice.add(sum);//---------最终价格1
           //---------最终价格（税后）
            orderItems.add(orderItem);
        }
        BigDecimal a = new BigDecimal('0');
        a=lastPrice;
        //设置税前
        piOrder.setPriceIt(a);
        BigDecimal b = new BigDecimal('0');
        BigDecimal c = new BigDecimal('0');
        BigDecimal taxRate = piOrder.getTaxRate();//税率
        b = lastPrice.multiply(taxRate);//税收
        c = a.add(b);//税后
        piOrder.setPriceit(c);//报价单显示总价（后）
        log.info("添加订单的价格开始");
        //设置税后价
        piOrder.setPrice(c);


        QueryWrapper qw = new QueryWrapper();
        if (id != null) {
            qw.eq("id", id);
        }
        orderMapper.update(piOrder, qw);//保存订单价格
        log.info("添加订单的价格结束");
        orderPri.setOrderItemList(orderItems);
        orderPri.setOrder(piOrder);//存入订单
        return orderPri;
    }

    @Override
    public List<XsPhoto> getXsPhoto() {
        return orderMapper.getXsPhoto();
    }

    @Override
    public List<XsPhoto> getmake() {
            return orderMapper.getmake();
    }
    @Override
    public List<XsPhoto> getcustomer() {
        return orderMapper.getcustomer();
    }
}
